﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Taurus.Platform.DTO;
using Taurus.Platform.Net;
using HtmlAgilityPack;
using System.Xml.Linq;
using Taurus.Garden.DTO;
using System.Threading;
using Newtonsoft.Json.Linq;

namespace Taurus.Garden.BLL
{
    class MyGarden
    {
        #region event
        public event EventHandler<ReturnMsgEventArgs> ReturnMessage;
        #endregion

        #region field

        private const string GARDEN_URL = "http://www.kaixin001.com/!house/garden/index.php";
        
        private const string MYGARDEN_INFO_URL = "http://www.kaixin001.com/!house/!garden//getconf.php?verify={0}";
        //收获果实
        private const string HARVEST_URL = "http://www.kaixin001.com/!house/!garden//havest.php?confirm=0&seedid=0&fuid=0&farmnum={0}";
        //犁地
        private const string PLOWING_URL = "http://www.kaixin001.com/!house/!garden//plough.php?confirm=0&seedid=0&fuid=0&farmnum={0}";
        //种子列表
        private const string SEED_LIST_URL = "http://www.kaixin001.com/!house/!garden/myseedlist.php?verify={0}&page={1}";
        //获取好友列表
        private const string FRIEND_URL = "http://www.kaixin001.com/!house/!garden/friendlist.php";
        //获取好友家的配置信息
        private const string FRIEND_GAREND_URL = "http://www.kaixin001.com/!house/!garden//getconf.php?verify={0}&fuid={1}";
        //偷取地址
        private const string STEAL_URL = "http://www.kaixin001.com/!house/!garden//havest.php?confirm=0&seedid=0&fuid={0}&farmnum={1}";
        //验证字段
        private string _verify = string.Empty;

        #endregion

        #region construction

        public MyGarden(UserAccount ua)
        {
            User = ua;
            MySeeds = new List<Seed>();
            
            UpdateInfo();
            UpdateMySeeds();
        }
        
        #endregion

        #region property

        public string Verify { get { return _verify; } }

        public UserAccount User { get; private set; }
        /// <summary>
        /// 技能等级
        /// </summary>
        public string Level { get; private set; }
        /// <summary>
        /// 我的现金
        /// </summary>
        public long Cash { get; private set; }
        /// <summary>
        /// 魅力
        /// </summary>
        public string Charms { get; private set; }
        /// <summary>
        /// 菜地
        /// </summary>
        public List<Vegetable> MyVegetable { get; private set; }
        /// <summary>
        /// 我的种子
        /// </summary>
        public List<Seed> MySeeds { get; set; }

        public List<Friend> MyFriends { get; set; }

        /// <summary>
        /// 备注信息，界面异步调用功能使用
        /// </summary>
        public string Remark { get; set; }
        #endregion


        #region private mothed

        private void UpdateInfo()
        {
            HtmlDocument doc = Util.AccessPage(User, GARDEN_URL);
            int s = doc.DocumentNode.InnerHtml.IndexOf("g_verify");
            s = doc.DocumentNode.InnerHtml.IndexOf("\"", s);
            int e = doc.DocumentNode.InnerHtml.IndexOf("\"", s + 1);
            _verify = doc.DocumentNode.InnerHtml.Substring(s + 1, e - s-1);

            doc = Util.AccessPage(User, string.Format(MYGARDEN_INFO_URL, _verify));
            MyVegetable = GetVegetableInfo(doc);
        }

        private List<Vegetable> GetVegetableInfo(HtmlDocument doc)
        {
            XDocument xdoc = XDocument.Parse(doc.DocumentNode.InnerHtml);
            XElement account = xdoc.Element("conf").Element("account");
            Level = account.Element("rank").Value;
            Cash = Util.GetNumber(account.Element("cashtip").Value);
            Charms = account.Element("tcharms").Value;

            List<Vegetable> retList = new List<Vegetable>();
            XElement garden = xdoc.Element("conf").Element("garden");
            foreach (var item in garden.Elements("item").ToList())
            {
                if (item.Element("visible").Value == "1")
                {
                    Vegetable vt = new Vegetable();
                    vt.HasGrass = item.Element("grass").Value != "0";
                    vt.HasVermin = item.Element("vermin").Value != "0";
                    vt.Water = int.Parse(item.Element("water").Value);
                    vt.IsShared = item.Element("shared").Value == "1";
                    vt.Farmnum = item.Element("farmnum").Value;
                    vt.HasPlowing = false;//默认不需要犁地

                    //notice:公共账号处理
                    if (InitSys.Instance.SeedMarketInstance == null)
                    {
                        InitSys.Instance.SeedMarketInstance = SeedMarket.BuildInstance(_verify, User);
                    }


                    if (item.Element("seedid") != null)
                    {
                        Seed seed = InitSys.Instance.SeedMarketInstance.GetSeed(item.Element("seedid").Value);
                        if (seed == null)
                        {
                            seed = InitSys.Instance.SeedMarketInstance.AddSeed(item.Element("seedid").Value, item.Element("name").Value);
                        }
                        vt.Seed = seed;
                        vt.HasPlowing = item.Element("wapcropspercent") == null;//被收割未犁地
                        if (!vt.HasPlowing)
                        {
                            //未被收割，枯死
                            vt.Percentage = item.Element("wapcropspercent").Value.Contains("剩余") ? "100%" : item.Element("wapcropspercent").Value;
                            if (item.Element("wapcropspercent").Value.Contains("剩余"))
                            {
                                vt.Count = HtmlTextNode.CreateNode(item.Element("wapcropspercent").Value).InnerText;
                            }
                            if (item.Element("wapcrops") != null)
                            {
                                vt.IsWilt = item.Element("wapcrops").Value == "已枯死";
                                vt.HasPicked = item.Element("wapcrops").Value.Contains("已摘过");
                            }
                        }
                        vt.FarmerName = item.Element("fuid").Value == "-1" ? User.Name : item.Element("friendname").Value;
                    }
                    else
                    {
                        vt.Seed = new Seed();
                    }
                    retList.Add(vt);
                }
            }
            return retList;
        }

        private void UpdateMySeeds()
        {
            int pageCount = 1;
            for (int i = 1; i <= pageCount; i++)
            {
                HtmlDocument doc = Util.AccessPage(User, string.Format(SEED_LIST_URL, _verify, i));
                XDocument xdoc = XDocument.Parse(doc.DocumentNode.InnerHtml);
                if (xdoc.Root.Element("ret").Value == "succ")
                {
                    pageCount = int.Parse(xdoc.Root.Element("totalpage").Value);
                    UpdateMySeeds(xdoc.Root.Element("seed"));
                }
                
            }
        }

        private void UpdateMySeeds(XElement seeds)
        {
            foreach (var item in seeds.Elements("item").ToList())
            {
                Seed seed = InitSys.Instance.SeedMarketInstance.GetSeed(item.Element("seedid").Value);
                if (seed == null)
                {
                    seed = InitSys.Instance.SeedMarketInstance.AddSeed(item.Element("seedid").Value, item.Element("name").Value);
                }
                seed.Count = int.Parse(item.Element("num").Value);
                MySeeds.Add(seed);
            }
        }

        private void UpdateFriends()
        {
            HtmlDocument doc = Util.AccessPage(User,FRIEND_URL);

            JArray ja = JArray.Parse(doc.DocumentNode.InnerHtml);
            var list = from u in ja
                       select new Friend()
                           {
                               UID = u.Value<string>("uid"),
                               Name = u.Value<string>("real_name"),
                               IsShare = u["share"] != null,
                               CanHarvest = u["harvest"] != null
                           };
            MyFriends = list.ToList();
        }

        private Message Harvest(Vegetable vegetable)
        {
            HtmlDocument doc = Util.AccessPage(User, string.Format(HARVEST_URL, vegetable.Farmnum));
            XDocument xdoc = XDocument.Parse(doc.DocumentNode.InnerHtml);
            Message msg = new Message();
            msg.IsSucc = xdoc.Root.Element("ret").Value == "succ";
            if (msg.IsSucc)
            {
                msg.Msg = string.Format("成功收获{0}个{1}", xdoc.Root.Element("leftnum").Value, xdoc.Root.Element("seedname").Value);
                vegetable.Count = string.Empty;
                vegetable.Percentage = string.Empty;
                vegetable.HasPlowing = true;
            }
            else
            {
                msg.Msg = string.Format("收获{0}失败", xdoc.Root.Element("seedname").Value);
            }
            return msg;
        }
        private Message Plowing(Vegetable vegetable)
        {
            HtmlDocument doc = Util.AccessPage(User, string.Format(PLOWING_URL, vegetable.Farmnum));
            XDocument xdoc = XDocument.Parse(doc.DocumentNode.InnerHtml);
            Message msg = new Message();
            msg.IsSucc = xdoc.Root.Element("ret").Value == "succ";
            if (msg.IsSucc)
            {
                vegetable.Seed = new Seed();//犁地成功,防止页面空绑定
                vegetable.HasPlowing = false;
            }
            if (xdoc.Root.Element("seedtips")!=null)
            {
                msg.Msg = xdoc.Root.Element("seedtips").Value;
            }
            return msg;
        }
        private Message Steal(Vegetable vegetable,Friend firend)
        {
            HtmlDocument doc = Util.AccessPage(User, string.Format(STEAL_URL, firend.UID, vegetable.Farmnum));
            XDocument xdoc = XDocument.Parse(doc.DocumentNode.InnerHtml);
            Message msg = new Message();            
            msg.IsSucc = xdoc.Root.Element("ret").Value == "succ";
            if (msg.IsSucc)
            {
                if (xdoc.Root.Element("anti").Value == "1")
                {
                    msg.IsSucc = false;
                    msg.Msg = "遭遇魔法仙女无法继续偷取";
                    return msg;
                }
                msg.Msg = string.Format("成功偷取{2}家{0}{1}个", xdoc.Root.Element("seedname").Value, xdoc.Root.Element("stealnum").Value, firend.Name);
            }
            else
            {
                msg.Msg = string.Format("偷取{0}家失败:{1}", firend.Name, xdoc.Root.Element("reason").Value);
                if (xdoc.Root.Element("reason").Value == "正在麻醉中，不能采摘")
                {
                    msg.Msg = "正在麻醉中，不能采摘";
                }
            }
            return msg;
        }


        #endregion

        #region public mothed

        public void Harvest()
        {
            foreach (var vegetable in MyVegetable)
            {
                if (!vegetable.IsShared && vegetable.Percentage == "100%")
                {
                    Message msg = Harvest(vegetable);
                    ReturnMessage(null, new ReturnMsgEventArgs() { Msg = msg });
                    Thread.Sleep(1500);
                    if (msg.IsSucc)
                    {
                        Message m = Plowing(vegetable);
                        ReturnMessage(null, new ReturnMsgEventArgs() { Msg = msg });
                    }
                    Thread.Sleep(1500);
                }
            }
        }

        public void Plowing()
        {
            foreach (var vegetable in MyVegetable)
            {
                if (!vegetable.IsShared && (vegetable.HasPlowing || vegetable.IsWilt))
                {
                    Message msg = Plowing(vegetable);
                    ReturnMessage(null, new ReturnMsgEventArgs() { Msg = msg });
                    Thread.Sleep(1500);
                }
            }
        }

        public void Steal()
        {
            UpdateFriends();
            foreach (var firend in MyFriends)
            {
                if (firend.CanHarvest)
                {
                    HtmlDocument doc = Util.AccessPage(User, string.Format(FRIEND_GAREND_URL, _verify, firend.UID));
                    List<Vegetable> vegetables = GetVegetableInfo(doc);
                    foreach (var item in vegetables)
                    {
                        if (!item.HasPicked && !item.IsShared && !item.IsWilt && item.Percentage=="100%")
                        {
                            Message msg = Steal(item, firend);
                            
                            ReturnMessage(null, new ReturnMsgEventArgs() { Msg = msg });
                            if (msg.Msg == "遭遇魔法仙女无法继续偷取" || msg.Msg == "正在麻醉中，不能采摘")
                            {
                                return;
                            }
                            Thread.Sleep(1500);
                        }
                    }
                }
            }
        }
        #endregion

    }
}
